//
//  NSString+BaseFramework.m
//  LotteryClient
//
//  Created by Sunyon 14-4-8.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "NSString+BaseFramework.h"
#import <CommonCrypto/CommonDigest.h>
#import <objc/runtime.h>

@implementation NSString (BaseFramework)

@end


@implementation NSString (Addition)

- (NSString *)md5String
{
    const char    *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);

    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                                       result[0],
                                       result[1],
                                       result[2],
                                       result[3],
                                       result[4],
                                       result[5],
                                       result[6],
                                       result[7],
                                       result[8],
                                       result[9],
                                       result[10],
                                       result[11],
                                       result[12],
                                       result[13],
                                       result[14],
                                       result[15]
    ] lowercaseString];
}


- (NSString *)substringFrom:(NSUInteger)a to:(NSUInteger)b
{
    NSRange r;
    r.location = a;
    r.length   = b - a;
    return [self substringWithRange:r];
}

- (NSInteger)indexOf:(NSString *)substring from:(NSUInteger)starts
{
    NSRange r;
    r.location = starts;
    r.length   = [self length] - r.location;

    NSRange index = [self rangeOfString:substring
                                options:NSLiteralSearch
                                  range:r];
    if (index.location == NSNotFound)
    {
        return -1;
    }
    return index.location + index.length;
}

- (BOOL)containsString:(NSString *)aString
{
    NSRange range = [[self lowercaseString] rangeOfString:[aString lowercaseString]];
    return range.location != NSNotFound;
}

- (BOOL)empty
{
    return [self length] <= 0;
}

- (BOOL)notEmpty
{
    return [self length] > 0;
}

- (NSString *)trim
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//转换时间格式
- (NSDate *)getFormatterDate
{
    //客户端的时期格式
    NSString *formatDateStr = [self stringByReplacingOccurrencesOfString:@"-"
                                                              withString:@""];
    formatDateStr = [formatDateStr stringByReplacingOccurrencesOfString:@":"
                                                             withString:@""];
    formatDateStr = [formatDateStr stringByReplacingOccurrencesOfString:@" "
                                                             withString:@""];
    //转化成NSDate
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    return [formatter dateFromString:formatDateStr];
}

+ (NSString *)dateFormatFromMillisecond:(NSString *)millisecond
{//将毫秒数换算成x天x时x分x秒x毫秒
    int      ms     = [millisecond intValue];
    int      ss     = 1000;
    int      mi     = ss * 60;
    int      hh     = mi * 60;
    int      dd     = hh * 24;
    //计算x天x时x分x秒x毫秒
    long     day    = ms / dd;
    long     hour   = (ms - day * dd) / hh;
    long     minute = (ms - day * dd - hour * hh) / mi;
    long     second = (ms - day * dd - hour * hh - minute * mi) / ss;
    //    long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
    NSString *strDay;
    NSString *strHour;
    NSString *strMinute;
    NSString *strSecond;
    //    NSString *strMilliSecond;
    if (day < 10)
    {
        strDay = [NSString stringWithFormat:@"0%ld",
                                            day];
    }
    else
    {
        strDay = [NSString stringWithFormat:@"%ld",
                                            day];
    }
    if (hour < 10)
    {
        strHour = [NSString stringWithFormat:@"0%ld",
                                             hour];
    }
    else
    {
        strHour = [NSString stringWithFormat:@"%ld",
                                             hour];
    }
    if (minute < 10)
    {
        strMinute = [NSString stringWithFormat:@"0%ld",
                                               minute];
    }
    else
    {
        strMinute = [NSString stringWithFormat:@"%ld",
                                               minute];
    }
    if (second < 10)
    {
        strSecond = [NSString stringWithFormat:@"0%ld",
                                               second];
    }
    else
    {
        strSecond = [NSString stringWithFormat:@"%ld",
                                               second];
    }
    //    if (milliSecond < 10)
    //        strMilliSecond = [NSString stringWithFormat:@"0%ld",milliSecond];
    //    else
    //        strMilliSecond = [NSString stringWithFormat:@"%ld",milliSecond];
    NSString *date;
    if (day != 0)
    {
        date = [NSString stringWithFormat:@"%@天%@小时",
                                          strDay,
                                          strHour];
    }
    else if (day == 0 && hour != 0)
    {
        date = [NSString stringWithFormat:@"%@小时%@分",
                                          strHour,
                                          strMinute];
    }
    else
    {
        date = [NSString stringWithFormat:@"%@分%@秒",
                                          strMinute,
                                          strSecond];
    }
    return date;
}


- (int)calculateTextNumber
{
    // Source: http://www.cocoachina.com/macdev/cocoa/2011/0110/2552.html
    int     i, n = [self length], l = 0, a = 0, b = 0;
    unichar c;
    for (i = 0; i < n; i++)
    {
        c = [self characterAtIndex:i];
        if (isblank(c))
        {
            b++;
        }
        else if (isascii(c))
        {
            a++;
        }
        else
        {
            l++;
        }
    }
    if (a == 0 && l == 0)
    {return 0;}
    return l + (int) ceilf((float) (a + b) / 2.0);
}

@end


@implementation NSString (FilePath)

static char *selfResourcePathKey = "selfResourcePath";

+ (NSString *)selfResourcePath
{
    NSString *path = objc_getAssociatedObject(self, selfResourcePathKey);
    if (!path || [path length] == 0)
    {
        return [self documentPath];
    }
    return path;
}

+ (void)setSelfResourcePath:(NSString *)path
{
    if (!objc_getAssociatedObject(self, selfResourcePathKey))
    {
        if (![self isExistsFile:path])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:path
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:nil];
        }
        objc_setAssociatedObject(self, selfResourcePathKey, path, OBJC_ASSOCIATION_RETAIN_NONATOMIC);


    }
}

//得到document路径
+ (NSString *)documentPath
{
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [searchPaths objectAtIndex:0];

    return documentPath;

}

+ (NSString *)cacheDirPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return paths[0];
}

+ (BOOL)isExistsDirectoryInDoc:(NSString *)DirName
{
    BOOL          isDir;
    BOOL          exists;
    NSFileManager *filemanage = [NSFileManager defaultManager];
    NSString      *realPath   = [[self documentPath] stringByAppendingPathComponent:DirName];
    exists = [filemanage fileExistsAtPath:realPath
                              isDirectory:&isDir];
    if (exists)
    {
        if (isDir)
        {
            return YES;
        }
    }
    return NO;

}

+ (BOOL)isExistsFileInDoc:(NSString *)fileName
{
    NSString *realPath = [[self documentPath] stringByAppendingPathComponent:fileName];

    return [self isExistsFile:realPath];
}

+ (BOOL)isExistsFile:(NSString *)fileFullName
{
    NSFileManager *filemanage = [NSFileManager defaultManager];
    return [filemanage fileExistsAtPath:fileFullName];
}

+ (BOOL)delFileInPath:(NSString *)filepath
{
    NSFileManager *filemanage = [NSFileManager defaultManager];
    if ([filemanage fileExistsAtPath:filepath])
    {
        NSError *error;

        return [filemanage removeItemAtPath:filepath
                                      error:&error];

    }
    return YES;
}

+ (BOOL)copyFile:(NSString *)sourcePath to:(NSString *)targetPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError       *error;
    if (![fileManager copyItemAtPath:sourcePath
                              toPath:targetPath
                               error:&error])
    {

        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    return YES;
}


+ (NSString *)filePathInBundleWithFileName:(NSString *)fileName
{
    NSString *type = [fileName pathExtension];

    fileName = [fileName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",
                                                                                         type]
                                                   withString:@""];

    return [[NSBundle mainBundle] pathForResource:fileName
                                           ofType:type];
}


+ (NSString *)filePathInBundleWithFileName:(NSString *)fileName
                                    ofType:(NSString *)type
{
    return [[NSBundle mainBundle] pathForResource:fileName
                                           ofType:type];
}

+ (NSString *)filePathInDocumentWithFileName:(NSString *)fileName
{
    return [[self documentPath] stringByAppendingFormat:@"/%@",
                                                        fileName];
}

+ (NSString *)filePathInDocumentWithFileName:(NSString *)fileName
                                      ofType:(NSString *)type
{
    return [[self documentPath] stringByAppendingFormat:@"/%@.%@",
                                                        fileName,
                                                        type];
}


+ (NSString *)filePathInSelfResourceWithFileName:(NSString *)fileName
{
    return [[self selfResourcePath] stringByAppendingFormat:@"/%@",
                                                            fileName];
}

+ (NSString *)filePathInSelfResourceWithFileName:(NSString *)fileName
                                          ofType:(NSString *)type
{
    return [[self selfResourcePath] stringByAppendingFormat:@"/%@.%@",
                                                            fileName,
                                                            type];
}


+ (NSString *)filePathInSelfResourceOrBundle:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString      *path        = [self filePathInSelfResourceWithFileName:fileName];
    if ([fileManager fileExistsAtPath:path])
    {
        return path;
    }
    else
    {
        return [self filePathInBundleWithFileName:fileName];
    }

}

//校验身份证号
+ (BOOL)validateIDCardNumber:(NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    int length = 0;
    if (!value)
    {
        return NO;
    }
    else
    {
        length = value.length;

        if (length != 15 && length != 18)
        {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray = @[@"11",
                            @"12",
                            @"13",
                            @"14",
                            @"15",
                            @"21",
                            @"22",
                            @"23",
                            @"31",
                            @"32",
                            @"33",
                            @"34",
                            @"35",
                            @"36",
                            @"37",
                            @"41",
                            @"42",
                            @"43",
                            @"44",
                            @"45",
                            @"46",
                            @"50",
                            @"51",
                            @"52",
                            @"53",
                            @"54",
                            @"61",
                            @"62",
                            @"63",
                            @"64",
                            @"65",
                            @"71",
                            @"81",
                            @"82",
                            @"91"
    ];

    NSString      *valueStart2 = [value substringToIndex:2];
    BOOL          areaFlag     = NO;
    for (NSString *areaCode in areasArray)
    {
        if ([areaCode isEqualToString:valueStart2])
        {
            areaFlag = YES;
            break;
        }
    }

    if (!areaFlag)
    {
        return false;
    }


    NSRegularExpression *regularExpression;
    NSUInteger          numberofMatch;

    int year = 0;
    switch (length)
    {
        case 15:
            year          = [value substringWithRange:NSMakeRange(6, 2)].intValue + 1900;

            if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0))
            {

                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];// 测试出生日期的合法性
            }
            else
            {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];// 测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];

            if (numberofMatch > 0)
            {
                return YES;
            }
            else
            {
                return NO;
            }
        case 18:

            year          = [value substringWithRange:NSMakeRange(6, 4)].intValue;
            if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0))
            {

                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];// 测试出生日期的合法性
            }
            else
            {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];// 测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];

            if (numberofMatch > 0)
            {
                int      S    = ([value substringWithRange:NSMakeRange(0,
                                                                       1)].intValue + [value substringWithRange:NSMakeRange(
                        10,
                        1)].intValue) * 7 + ([value substringWithRange:NSMakeRange(1,
                                                                                   1)].intValue + [value substringWithRange:NSMakeRange(
                        11,
                        1)].intValue) * 9 + ([value substringWithRange:NSMakeRange(2,
                                                                                   1)].intValue + [value substringWithRange:NSMakeRange(
                        12,
                        1)].intValue) * 10 + ([value substringWithRange:NSMakeRange(3,
                                                                                    1)].intValue + [value substringWithRange:NSMakeRange(
                        13,
                        1)].intValue) * 5 + ([value substringWithRange:NSMakeRange(4,
                                                                                   1)].intValue + [value substringWithRange:NSMakeRange(
                        14,
                        1)].intValue) * 8 + ([value substringWithRange:NSMakeRange(5,
                                                                                   1)].intValue + [value substringWithRange:NSMakeRange(
                        15,
                        1)].intValue) * 4 + ([value substringWithRange:NSMakeRange(6,
                                                                                   1)].intValue + [value substringWithRange:NSMakeRange(
                        16,
                        1)].intValue) * 2 + [value substringWithRange:NSMakeRange(7,
                                                                                  1)].intValue * 1 + [value substringWithRange:NSMakeRange(
                        8,
                        1)].intValue * 6 + [value substringWithRange:NSMakeRange(9, 1)].intValue * 3;
                int      Y    = S % 11;
                NSString *M   = @"F";
                NSString *JYM = @"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y, 1)]; // 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17, 1)]])
                {
                    return YES;// 检测ID的校验位
                }
                else
                {
                    return NO;
                }

            }
            else
            {
                return NO;
            }
        default:
            return NO;
    }
}

// 正则判断手机号码地址格式
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
    * 手机号码18310934585
    * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    * 联通：130,131,132,152,155,156,185,186
    * 电信：133,1349,153,180,189
    */
    NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
    10         * 中国移动：China Mobile
    11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
    12         */
    NSString *CM     = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
    15         * 中国联通：China Unicom
    16         * 130,131,132,152,155,156,185,186
    17         */
    NSString *CU     = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
    20         * 中国电信：China Telecom
    21         * 133,1349,153,180,189
    22         */

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
                                                                    MOBILE];
    NSPredicate *regextestcm     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
                                                                    CM];
    NSPredicate *regextestcu     = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
                                                                    CU];
    //    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];

    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end

@implementation NSString (urlEncoding)

+ (NSString *)URLEncodedString:(NSString *)string withCFStringEncoding:(CFStringEncoding)encoding
{
    return (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                 (__bridge CFStringRef) [string mutableCopy],
                                                                 NULL,
                                                                 CFSTR("￼=,!$&'()*+;@?\n\"<>#\t :/"),
                                                                 encoding);
}

+ (NSString *)URLEncodedString:(NSString *)string
{
    return [self URLEncodedString:string
             withCFStringEncoding:kCFStringEncodingUTF8];
}


- (NSString *)urlEncoding
{
    NSString *result = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                            (__bridge CFStringRef) self,
                                                                            NULL,
                                                                            CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                            kCFStringEncodingUTF8);
    return result;
}

- (NSString *)urlDecoding
{
    NSMutableString *outputStr = [NSMutableString stringWithString:self];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];

    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)valueForUrlParameterName:(NSString *)parameterName
{
//    if ([self containsString:parameterName])
//    {
//        NSRange range = [self rangeOfString:parameterName];
//        NSString *resultString = [self substringFromIndex:range.location];
//
//    }
//    else
//    {
//        return nil;
//    }
    return nil;
}
@end

